from typing import List, Sequence

from sqlalchemy.ext.asyncio import AsyncSession

from app.crud.demo import select_all, select_by_id, insert, update_by_id, delete_by_id, delete_by_ids, page, \
    select_by_ids
from app.models.demo import PythonModel
from app.schemas.base_schema import PageParam, PageResult
from app.schemas.demo import PythonModelDTO, PythonModelVO
from app.utils.convert import pydantic_to_model, models_to_pydantic, model_to_pydantic


class PythonModelService:
    """
    PythonModel 业务逻辑处理类

    提供对 PythonModel 表数据的增删改查等业务操作，
    负责处理数据转换、业务逻辑判断等任务。
    """

    @staticmethod
    async def page(db: AsyncSession, param: PageParam[PythonModelDTO]) -> PageResult[PythonModelVO]:
        """
        分页查询

        :param db: 数据库会话对象
        :param param: 分页查询参数
        :return: 分页结果
        """
        # DTO -> Entity
        entity: PythonModel = pydantic_to_model(param.model, PythonModel)

        # 构造过滤条件
        filters = []
        for column in PythonModel.__mapper__.c.keys():
            value = getattr(entity, column, None)
            if value is None:
                continue
            filters.append(getattr(PythonModel, column) == value)

        # 分页查询
        lists, count = await page(db, param.page, param.limit, filters, param.sort, param.order)
        # Entity -> VO
        records: Sequence[PythonModelVO] = models_to_pydantic(lists, PythonModelVO)
        return PageResult[PythonModelVO](list=records, count=count)

    @staticmethod
    async def list(db: AsyncSession, param: PythonModel) -> Sequence[PythonModelVO]:
        """
        批量查询

        :param db: 数据库会话对象
        :param param: 批量查询查询参数
        :return: 查询结果
        """
        # 批量查询
        lists: Sequence[PythonModel] = await select_all(db, param)
        # Entity -> VO
        return models_to_pydantic(lists, PythonModelVO)

    @staticmethod
    async def get(db: AsyncSession, id: int) -> PythonModelVO | None:
        """
        通过id查询数据

        :param db: 数据库会话对象
        :param id: 主键
        :return: 查询到的数据，未找到返回 None
        """
        entity = await select_by_id(db, id)
        if entity is None:
            return None
        return model_to_pydantic(entity, PythonModelVO)

    @staticmethod
    async def save(db: AsyncSession, param: PythonModel) -> bool:
        """
        保存

        :param db: 数据库会话对象
        :param param: 保存的参数
        :return: 成功返回True，失败返回False
        """
        result = await insert(db, param)
        return result > 0

    @staticmethod
    async def update(db: AsyncSession, param: PythonModel) -> bool:
        """
        更新

        :param db: 数据库会话对象
        :param param: 更新的参数，id不能为空
        :return: 成功返回True，失败返回False
        """
        result = await update_by_id(db, param)
        return result > 0

    @staticmethod
    async def delete(db: AsyncSession, id: int) -> bool:
        """
        通过id删除数据

        :param db: 数据库会话对象
        :param id: 主键
        :return: 成功返回True，失败返回False
        """
        # 删之前查一下
        entity = await select_by_id(db, id)
        if entity is None:
            return True
        # 删除
        result = await delete_by_id(db, id)
        return result > 0

    @staticmethod
    async def batch_delete(db: AsyncSession, ids: List[int]) -> bool:
        """
        批量删除

        :param db: 数据库会话对象
        :param ids: 主键列表
        :return: 成功返回True，失败返回False
        """
        # 删之前查一下
        entities = await select_by_ids(db, ids)
        if len(entities) == 0:
            return True

        result = await delete_by_ids(db, ids)
        return result > 0
